package org.dandsoft.blackbox.mapreduce.client.task;

import java.util.Set;
import java.util.HashSet;

/**
 * @author Vilyuzhanin Denis (Fin)
 */
public class ActionsQueue {

    private Task task;
    private Set<String> queue = new HashSet<String>();
    private Set<String> executedActions = new HashSet<String>();

    public ActionsQueue(Task task) {
        this.task = task;
        queue.addAll(task.getActions());
    }

    public Set<String> nextActions() {
        HashSet<String> result = new HashSet<String>();
        for (String action : queue) {
            boolean isReady = true;
            for (String dep : task.getDependencies(action)) {
                //если зависимость еще не выполнялась и это не регистр, то действие еще не готово
                if (queue.contains(dep) && task.getActionType(dep) != ActionType.Register) {
                    isReady = false;
                    break;
                }
            }
            if (isReady) {
                result.add(action);
            }
        }
        return result;
    }

    public boolean isFinish() {
        return queue.size() == 0;
    }

    public boolean isDeadLock() {
        return queue.size() > 0 && nextActions().size() == 0;
    }

    public void setExecuted(String action) {
        if (queue.remove(action)) {
            executedActions.add(action);
        }
    }

    public void setExecuted(Set<String> actions) {
        for (String action : actions) {
            setExecuted(action);
        }
    }

    public Set<String> getQueue() {
        return queue;
    }

    public Set<String> getExecutedActions() {
        return executedActions;
    }

    public Task getTask() {
        return task;
    }


}
